package com.kaoqin.util;

import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;

public final class ResponseUtils {

	public static final Logger log = LoggerFactory.getLogger(ResponseUtils.class);

	public ResponseUtils() {
	}

	public static void renderText(HttpServletResponse response, String text) {
		render(response, "text/plain;charset=UTF-8", text);
	}

	public static void renderJson(HttpServletResponse response, String text) {
		render(response, "application/json;charset=UTF-8", text);
	}

	public static void renderXml(HttpServletResponse response, String text) {
		render(response, "text/xml;charset=UTF-8", text);
	}

	public static void renderHtml(HttpServletResponse response, String text) {
		render(response, "text/html; charset=UTF-8", text);
	}

	public static void echoJson(HttpServletResponse response, Integer code) {
		echoJson(response, code, null, null);
	}

	public static void echoJson(HttpServletResponse response, Integer code, String msg, Object res) {
		response.setContentType("text/html; charset=UTF-8");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0L);
		try {
			msg = StringUtils.isNotBlank(msg) ? msg : "";
			Map<String, Object> result = new TreeMap<>();
			result.put("code", code);
			if (StringUtils.isNotBlank(msg)) {
				result.put("message", msg);
			}
			if (null != res) {
				result.put("result", res);
			}
			response.getWriter().write(new Gson().toJson(result));
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}
	}

	public static void render(HttpServletResponse response, String contentType, String text) {
		response.setContentType(contentType);
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0L);
		try {
			response.getWriter().write(text);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}
	}
}
